package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/juju/ratelimit"
	"net/http"
	"time"
)

func RateLimitMiddleware(fillInterval time.Duration, cap int64) func(c *gin.Context) {
	bucket := ratelimit.NewBucket(fillInterval, cap)
	return func(c *gin.Context) {
		if bucket.TakeAvailable(1) < 1 {
			fmt.Println(time.Now().Format("2006-01-02 15:04:05.000"))
			c.String(http.StatusOK, "rate limit...")
			c.Abort()
			return
		}
		c.Next()
	}
}

func main() {
	r := gin.New()
	fillInterval := 20 * time.Second
	r.GET("/", RateLimitMiddleware(fillInterval, 2), func(c *gin.Context) {
		c.String(http.StatusOK, "this main")
	})
	_ = r.Run(":8000")
}
